# coding: utf-8
import json

import scrapy
from lxml.doctestcompare import strip

from sqlalchemy import func, select

from ..enum.TipTypeEnum import TipType
from ..helpers import sql as sql

from scrapy.http import JsonRequest

from ..helpers import globals as globals
from ..helpers import list_test as list_test
from ..pojo import all_model as all_model
from ..enum import TipTypeEnum as tipType
from sqlalchemy.orm import sessionmaker
import time

class XiongmaozikaoSpider(scrapy.Spider):
    name = "XiongMaoZiKao"
    allowed_domains = ["app.online.xiongmaozikao.com"]

    def start_requests(self):
        req = []
        for paper in list_test.paperList:
            url = globals.domain + globals.subjectApi + '?id=' + paper['id'] + '&num=2'
            print(url)
            req.append(JsonRequest(url,
                                   method='get',
                                   headers=globals.header,
                                   cb_kwargs=dict(id=paper['id'], paper_id=paper['paper_id'],
                                                  tk_type_id=paper['tk_type_id'], paper_name=paper['paper_name'],
                                                  exam_type_id_var=paper['exam_type_id']), callback=self.parse))
        return req

    def parse(self, response, id, paper_id, tk_type_id, paper_name, exam_type_id_var):
        jsonData = json.loads(response.text)

        with open("attachment/"+id+".txt", "w", encoding="utf-8") as file:
            # 读取文件内容
            file.write(response.text)
            # 打印文件内容
            print('ok')

        timestamp = int(time.time())
        engine = sql.getEngine(self, response)
        session = sessionmaker(engine)()
        session.begin()

        q = session.query(all_model.KaotikuPaper).filter(all_model.KaotikuPaper.name == paper_name,
                                                         all_model.KaotikuPaper.exam_type_id == exam_type_id_var)
        result = q.scalar()
        if result:
            print(str(q))
            print('已存在试卷' + paper_name + '--' + f"{exam_type_id_var}")
            return

        try:
            maxId = session.query(func.max(all_model.KaotikuSubject.id)).scalar()
            maxAnswerId = session.query(func.max(all_model.KaotikuSubjectAnswer.id)).scalar()
            maxPaperId = session.query(func.max(all_model.KaotikuPaper.id)).scalar()
            maxPaperChapterId = session.query(func.max(all_model.KaotikuPaperChapter.id)).scalar()

            maxId = 1 if maxId is None else maxId
            maxAnswerId = 1 if maxAnswerId is None else maxAnswerId
            maxPaperId = 1 if maxPaperId is None else maxPaperId
            maxPaperChapterId = 1 if maxPaperChapterId is None else maxPaperChapterId

            # 一个parse一张试卷
            maxPaperId = maxPaperId + 1

            # 添加试卷
            paper = all_model.KaotikuPaper(id=maxPaperId, p_content=paper_id, exam_type_id=exam_type_id_var, name=paper_name,
                                           status=1, create_time=timestamp, update_time=timestamp)

            session.add_all([paper])
            subjectIds = []
            objects = []
            nowTipType = None
            nowChapterId = 0
            for ques in jsonData['data']['list']:
                q = session.query(all_model.KaotikuSubjectVersion).filter(
                    all_model.KaotikuSubjectVersion.tip_str == ques['title'],
                    all_model.KaotikuSubjectVersion.tip_type == tk_type_id)
                if q.scalar():
                    print('已存在试题' + ques['title'])
                    continue

                maxId = maxId + 1
                tempTipType = tipType.get_ques_key(ques['questionType'])
                if nowTipType is None or tempTipType != nowTipType:  # 创建章节
                    nowTipType = tipType.get_ques_key(ques['questionType'])
                    maxPaperChapterId = maxPaperChapterId + 1

                    chapter = all_model.KaotikuPaperChapter(id=maxPaperChapterId, stype=1, ptype=1, name=tipType.get_map()[nowTipType],
                                                  subject_type_ids=tk_type_id, paper_id=paper.id, tip_type=nowTipType,
                                                  level='common', create_time=timestamp, update_time=timestamp)
                    objects.append(chapter)
                    nowChapterId = chapter.id

                subject = all_model.KaotikuSubject(id=maxId, level='common', type_id=tk_type_id, p_content=id + ',xm,py',
                                                   status=1, create_time=timestamp, update_time=timestamp)

                version = all_model.KaotikuSubjectVersion(id=maxId, tip_str=ques['title'],
                                                          tip_type=tipType.get_ques_key(ques['questionType']),
                                                          subject_id=maxId,status=1,create_time=timestamp,
                                                          short_answer=ques['description'])
                objects.append(subject)
                objects.append(version)
                subjectIds.append(maxId)

                answersArray = ques['content']
                if nowTipType == TipType.SINGLE.value or nowTipType == TipType.MULTI.value or nowTipType == TipType.JUDGE.value:
                    for answers in answersArray:
                        maxAnswerId = maxAnswerId + 1
                        rightAnswerInt = 1 if ques['rightAnswer'].find(answers['name']) != -1 else 0

                        answersDb = all_model.KaotikuSubjectAnswer(id=maxAnswerId, create_time=timestamp, update_time=timestamp,
                                                       answer=answers['value'], p_content=answers['name'], right_answer=rightAnswerInt,
                                                       answer_note=ques['description'], version_id=maxId, status=1)
                        objects.append(answersDb)
                else:
                    maxAnswerId = maxAnswerId + 1
                    answersDb = all_model.KaotikuSubjectAnswer(id=maxAnswerId, create_time=timestamp,
                                                               update_time=timestamp,
                                                               answer=ques['rightAnswer'], answer_note=ques['description'],
                                                               right_answer=1, version_id=maxId,
                                                               status=1)
                    objects.append(answersDb)
                defaultWeigh = 50
                for subjectId in subjectIds:
                    paper_subject = all_model.KaotikuPaperSubject(subject_id=subjectId, paper_id=paper.id, chapter_id=nowChapterId)
                    defaultWeigh = defaultWeigh + 1
                    objects.append(paper_subject)

                session.add_all(objects)
                session.commit()
        except Exception as e:
            session.rollback()
            raise e
            # print(f"发生了异常：{e}")
        finally:
            session.close()










